/**
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#if DEBUG_VERSION
if (!dafos) {
  throw new Error("Dafos namespace not found!");
}
#endif

#if EXPORTTAB

dafos.onExportTabActivated = function() {
  if (dafos.exporttab == null) {
    dafos.exporttab = new dafos.ExportTab(document.getElementById("exporttab"), dafos.ui);
  }
  TRACK("tab/export");
  RESIZE();
};

/**
 * Constructor
 */
dafos.ExportTab = function(parent, ui) {
  LOG("[ExportTab]");
  this.appengine = new dafos.AppEngine();
  
  var callbacks = {
      "savespecas": dafos.bind(this.saveAs, this),
      "savespec": dafos.bind(this.save, this),
      "loadspec": dafos.bind(this.load, this),
      "deletespec": dafos.bind(this.deleteSpec, this),
      "exportspec": dafos.bind(this.exportSpec, this)
  };
  this.gadgetui = ui;
  this.ui = new dafos.ExportTabUI(parent, callbacks);
  
  this.gadgetui.showLoading("specs");
  this.appengine.getOwnerXmlSpecs(dafos.bind(this.onXmlSpecsLoaded, this));
  
  this.templates = {};
  this.gadgetui.showLoading("xml-template");
  dafos.initCallback.getCallback();
  this.appengine.getXmlTemplate(this.closeOnTemplateLoaded("xml-template"));
    
  dafos.initCallback.addOnFinishedListener(dafos.bind(this.onTemplatesLoaded, this));
  
  this.current_spec_id_ = null;
  this.current_spec_name_ = null;
};

  
dafos.ExportTab.prototype.closeOnTemplateLoaded = function(template) {
  var me = this;
  return function (data) {
    LOG("[onTemplateLoaded]", "data", data);
    me.gadgetui.hideLoading(template);
    me.templates[template] = data || "";
    dafos.initCallback.callback(); 
  };
};

dafos.ExportTab.prototype.onTemplatesLoaded = function() {
  LOG("[onTemplatesLoaded]");
  this.ui.renderExportButton();
};


dafos.ExportTab.prototype.onXmlSpecsLoaded = function(data) {
  LOG("[onXmlSpecsLoaded]", "data", data);
  this.gadgetui.hideLoading("specs");
  
  this.gadgetui.setMessage(data.message);
  if (data.status == "success") {
    this.specs_ = {};
    for (var i = 0; i < data.payload.length; i++) {
      this.specs_[data.payload[i].id] = data.payload[i];
    }
    this.ui.renderXmlSpecList(this.specs_);
  }
};

dafos.ExportTab.prototype.saveAs = function() {
  LOG("[saveXmlSpecAs]");
  var input = new ark.InputDisplay(document.body);
  var me = this;
  input.show("Save XML spec as?", function (desired_name) { 
    if (desired_name) {
      me.current_spec_name_ = desired_name;
      me.save.apply(me); 
    }
    TRACK("action/savexmlspecas");
  });
};

dafos.ExportTab.prototype.save = function () {
  LOG("[saveXmlSpec]");
  if (!this.current_spec_name_) {
    this.saveAs.apply(this);
  } else {
    this.gadgetui.showLoading("save");
    this.appengine.saveXmlSpec(
        this.current_spec_name_, 
        gadgets.json.stringify(this.ui.getFormData()),
        dafos.opensocial.viewer && dafos.opensocial.viewer.getDisplayName && dafos.opensocial.viewer.getDisplayName(),
        dafos.bind(this.onSaved, this));
  }
  TRACK("action/savexmlspec");
};

dafos.ExportTab.prototype.onSaved = function(data) {
  LOG("[onXmlSpecSaved]", "data", data);
  this.gadgetui.hideLoading("save");
  
  this.gadgetui.setMessage(data.message);
  if (data.status == "success") {
    this.current_spec_name_ = data.payload.name;
    this.current_spec_id_ = data.payload.id;
    this.specs_[data.payload.id] = data.payload;
    this.ui.renderXmlSpecList(this.specs_);
    this.ui.setCurrentSpec(this.current_spec_name_, this.current_spec_id_);
  }
};

dafos.ExportTab.prototype.load = function() {
  LOG("[load]");
  this.current_spec_name_ = this.ui.getNameToLoad();
  this.current_spec_id_ = this.ui.getIdToLoad();
  LOG("name", this.current_spec_name_, "id", this.current_spec_id_);
  this.gadgetui.showLoading("load");
  this.appengine.getXmlSpec(this.current_spec_id_,
      dafos.bind(this.onLoaded, this));
  TRACK("action/loadxmlspec");
};

dafos.ExportTab.prototype.onLoaded = function(data) { 
  LOG("[onLoaded]", "data", data);
  this.gadgetui.hideLoading("load");
    
  this.gadgetui.setMessage(data.message);
  if (data.status == "success") {
    this.ui.setFormData(gadgets.json.parse(data.payload.text));
    this.ui.setCurrentSpec(this.current_spec_name_, this.current_spec_id_);
  }
};

dafos.ExportTab.prototype.deleteSpec = function() {
  LOG("[deleteSpec]");
  this.gadgetui.showLoading("delete");
  this.appengine.deleteRecord(this.current_spec_id_,
      dafos.bind(this.onDeleted, this));
  TRACK("action/loadxmlspec");
};

dafos.ExportTab.prototype.onDeleted = function(data) {
  LOG("[onDeleted]", data);
  this.gadgetui.hideLoading("delete");
    
  this.gadgetui.setMessage(data.message);
  if (data.status == "success") {
    delete this.specs_[this.current_spec_id_];
    this.ui.renderXmlSpecList(this.specs_);
    this.current_spec_id_ = null;
    this.current_spec_name_ = null;
    this.ui.setCurrentSpec("", "");
  }
};

dafos.ExportTab.prototype.exportSpec = function() {
  var formdata = this.ui.getFormData();
  LOG("[exportSpec]", formdata, this.templates);
  var features = [];
  var preloads = [];
  var views = [];
  var template = this.templates["xml-template"];
  for (var key in formdata) {
    if (formdata.hasOwnProperty(key)) {
      if (this.isFeatureCheckboxKey_(key)) {
        //Is a feature
        var feature = this.getFeatureString_(key, formdata);
        if (feature) {
          features.push(feature);
        }
      } else if (key == "preloads") {
        //Is a preload
        for (var i = 0, preload; preload = formdata[key][i]; i++) {
          preloads.push(this.getPreloadString_(preload));
        }
      } else if (key == "views") {
        for (var viewname in formdata[key]) {
          var view = formdata[key][viewname];
          views.push(this.getViewString_(viewname, view));
        }
      } else {
        //Direct substitution of remaining form fields
        var regexp = new RegExp("@" + key + "@", "g");
        template = template.replace(regexp, formdata[key]);
      }
    }
  }

  var features_regexp = new RegExp("@export-features@", "g");
  template = template.replace(features_regexp, features.join("\n"));

  var preloads_regexp = new RegExp("@export-preloads@", "g");
  template = template.replace(preloads_regexp, preloads.join("\n"));

  var views_regexp = new RegExp("@export-views@", "g");
  template = template.replace(views_regexp, views.join("\n"));
  
  this.ui.renderExportOutput(template);
  TRACK("action/exportxmlspec");
};

dafos.ExportTab.prototype.getViewString_ = function(name, view) {
  return [ 
    '<Content type="html" view="' + name + '">',
    '  <![CD' + 'ATA[',
    view.html,
    '  ]', ']>',
    '</Content>' 
  ].join("\n");
};

dafos.ExportTab.prototype.getPreloadString_ = function(preload) {
  var str = '<Preload href="' + preload["export-preload-href"] + '"';
  
  if (preload["export-preload-auth"] == "signed") {
    str += ' authz="signed"';
    if (preload["export-preload-sign-viewer"] == true ) {
      str += ' sign_viewer="true"';
    }
    if (preload["export-preload-sign-owner"] == true ) {
      str += ' sign_owner="true"';
    }
  }
  
  str += '>';
  return str;
};

dafos.ExportTab.prototype.isFeatureCheckboxKey_ = function(key) {
  return key.indexOf("export-features-") == 0 && 
         key.indexOf("-type") == -1;
};

dafos.ExportTab.prototype.getFeatureString_ = function(key, formdata) {
  if (formdata[key] == true) {
    var feature = key.substring(16);
    var type = (formdata[key + "-type"] == "required") ? "Require" : "Optional";
    return  "<" + type + " feature=\"" + feature + "\" />";
  }
  return null;
};

/**
 * Constructor
 */
dafos.ExportTabUI = function(parent, callbacks) {
  LOG("[ExportTabUI]");
  this.dom_parent_ = parent;
  this.callbacks_ = callbacks;
  this.toolbar_ = e34.$("exporttab_toolbar");
  this.toolbar_left_ = e34.$("exporttab_toolbar_leftbuttons");
  this.toolbar_right_ = e34.$("exporttab_toolbar_rightbuttons");
  this.filename_toolbar_ = e34.$("exporttab_filename");
  this.filename_label_ = e34.$("exporttab-loaded-file");
  this.preload_id_counter = 0;
  this.views_ = {};
  this.render();
};

dafos.ExportTabUI.prototype.render = function() {
  //Unhide the content area
  e34.$("exporttab").removeClass("hidden");
  
  //Set up the "add a preload" button
  e34.$("export-preload-button-add").addOnClickHandler(dafos.bind(
      this.handleAddPreload, this));
  this.preload_table = e34.$("export-preload-table");
  this.preload_template = e34.$("export-preload-template");
  this.preload_parent = e34.$(this.preload_template.getParentElement());
  
  this.preload_table.hide();
  this.preload_template.removeFromParent();
  
  //Hide the loaded file toolbar
  this.filename_toolbar_.hide();
  
  //Set up the features checkboxes to toggle their corresponding selects
  this.forEachFeatureCheckbox(function(checkbox, select, feature_name) { 
    checkbox.addOnClickHandler(function() { 
      if(checkbox.getValue() == true) {
        select.enable();
      } else {
        select.disable();
      }
    });
  });
  
  var me = this;
  
  //Set up the "load" button before the list because the callbacks will be 
  //fired when we assign them
  this.load_button_ = new e34widgets.IconLink(
          "export-load-button", 
          "@server.deploy.base@/img/load.png", 
          "Load")
      .addClass("dafos-button")
      .addOnClickHandler(this.callbacks_.loadspec);
  
  //Set up the saved items list
  this.xmlspecs_list_ = new e34widgets.DropDown(
          "export-saved-entries-list",
          this.toolbar_left_)
      .addOnItemsHandler(function() { this.show(); me.load_button_.show(); LOG("yay", this); })
      .addOnEmptyHandler(function() { this.hide(); me.load_button_.hide(); });
  
  //Add the load button after the list
  this.load_button_.setParent(this.toolbar_left_);
  
  if (dafos.cansave) {
    //Set up the "save as" button
    this.saveas_button_ = new e34widgets.IconLink(
            "export-saveas-button", 
            "@server.deploy.base@/img/saveas.png", 
            "Save XML spec as", 
            this.toolbar_left_)
        .addClass("dafos-button")
        .addOnClickHandler(this.callbacks_.savespecas);
    
    this.save_button_ = new e34widgets.IconLink(
        "export-save-button", 
        "@server.deploy.base@/img/save.png", 
        "Save",
        this.filename_toolbar_)
    .addClass("dafos-button")
    .addOnClickHandler(this.callbacks_.savespec);
    
    this.delete_button_ = new e34widgets.IconLink(
        "export-delete-button", 
        "@server.deploy.base@/img/delete.png", 
        "Delete",
        this.filename_toolbar_)
    .addClass("dafos-button")
    .addOnClickHandler(this.callbacks_.deletespec);
  }
  
  //Set up the views section
  this.view_parent_ = e34.$("exporttab-view-tabs").getElement();
  this.view_template_ = e34.$("exporttab-view-template").removeFromParent();
  this.view_tabs_ = new gadgets.TabSet("exporttab-views", null, this.view_parent_);
  this.view_tabs_.alignTabs("left", 10);
  
  //Delete the delete button from the first view tab
  this.addNewView("canvas").$C("view_delete")[0].removeFromParent();
  
  e34.$("exporttab-view-button-add").addOnClickHandler(dafos.bind(this.onNewViewClicked, this));
  
  
  
  var overlay_template = e34.$("exporttab-overlay-template").removeFromParent();

  this.overlay_ = new e34widgets.Overlay(
        "export-overlay", 
        "80%", 
        "50px", 
        this.dom_parent_)
    .addClass("overlay-shadow")
    .addContentClass("overlay-content")
    .setContent(overlay_template)
    .hide();
    
  this.textbox_ = overlay_template.$("exporttab-overlay-textbox")
    .setStyleHeight("400px");
    
#if EVILPREVIEWMODE
  this.previewiframe_ = overlay_template.$("exporttab-overlay-preview-iframe");
  this.previewform_ = overlay_template.$("exporttab-overlay-preview-form");
  this.previewform_["container"] = overlay_template.$("exporttab-form-container");
  this.previewform_["rawxml"] = overlay_template.$("exporttab-form-rawxml");
  this.previewform_["view"] = overlay_template.$("exporttab-form-view");
  this.previewform_["synd"] = overlay_template.$("exporttab-form-synd");
  this.previewform_["libs"] = overlay_template.$("exporttab-form-libs");
  this.previewform_["st"] = overlay_template.$("exporttab-form-st");
  
  LOG("preview iframe:", this.previewiframe_, window.location.href);
#endif

  var me = this;

  //Handle clicks of the "Close" button
  overlay_template.$("exporttab-overlay-button").addOnClickHandler(function (e) {
    me.overlay_.hide();
    if (e.stopPropagation) {
      e.stopPropagation();
    }
    return false;
  });
  
  //Handle clicks of the "Copy to Clipboard" button
  overlay_template.$("exporttab-overlay-clipboard-button").addOnClickHandler(function(e) {
    if (me.copyElementContent(me.textbox_)) {
      if (e.stopPropagation) {
        e.stopPropagation();
      }
      return false;
    } else {
      LOG("Defaulting to copy via flash method");
    }
  });
};

dafos.ExportTabUI.prototype.renderExportButton = function() {
  this.export_button_ = new e34widgets.IconLink(
          "export-export-button",
          "@server.deploy.base@/img/execute.png",
          "Export",
          this.toolbar_right_)
      .addClass("dafos-button")
      .addOnClickHandler(this.callbacks_.exportspec);
  
  //Add a button to the bottom, as well
  new e34widgets.IconLink(
      "export-export-button-bottom",
      "@server.deploy.base@/img/execute.png",
      "Export",
      e34.$("exporttab-bottom-toolbar"))
  .addClass("dafos-button")
  .addOnClickHandler(this.callbacks_.exportspec);
};

dafos.ExportTabUI.prototype.forEachFeatureCheckbox = function(callback) {
  var features_table = e34.$("features-table");
  var checkboxes = features_table.$C("input", "input");
  for (var i = 0, checkbox; checkbox = checkboxes[i]; i++) {
    var checkbox_id = checkbox.getId();
    var feature_name = checkbox_id.replace(/export-features-/, "");
    var select = e34.$(checkbox_id + "-type");
    callback(checkbox, select, feature_name);
  }  
};

dafos.ExportTabUI.prototype.renderXmlSpecList = function(specs) {
  this.xmlspecs_list_.clearOptions();
  for (var id in specs) {
    if (specs.hasOwnProperty(id)) {
      this.xmlspecs_list_.addOption(id, specs[id].name);
    }
  }
  gadgets.window.adjustHeight();
};

dafos.ExportTabUI.prototype.addNewView = function(name) {
  if (this.views_[name]) {
    return this.views_[name];
  }
  
  var view = e34.renderTemplate(this.view_template_, {
    "name": name
  }); 
  
  var textarea_bg = view.$C("view_html_background")[0];
  var textarea = view.$C("view_html")[0];
  var script_regex = new RegExp("(<sc" + "ript((?:.|\r\n|\n))*?</scr" + "ipt>)", "mgi");
  var timer = null;
  //Change the background when the text in the textarea changes
  var keylistener = function(e) {
    window.clearTimeout(timer);

    timer = window.setTimeout(function() {
      var newtext = textarea.getValue();
      
      if (newtext.search(script_regex) > -1) {
        newtext = newtext.replace(script_regex, "@@@$1%%%")
      }
      newtext = newtext.replace(/(\r\n|\n)/gim, "[br]");
      newtext = gadgets.util.escapeString(newtext)
          .replace(/@@@/g, "<span class='highlight'>")
          .replace(/%%%/g, "</span>")
          .replace(/\[br\]/g, "<br />")
          .replace(/[ ]{2}/g, "&nbsp; ");
      
      textarea_bg.getElement().innerHTML = newtext + "\n&nbsp;";
    }, 50);
  };
  
  //Add the key press listener to update the background
  textarea.addListener("keypress", keylistener, true);
  
  //Match the scrolling of both text areas
  textarea.addListener("scroll", function(e) {
    textarea_bg.getElement().scrollTop = textarea.getElement().scrollTop
  }, true);
  
  //Set up the "load javascript from code tab" functionality
  view.$C("view_copy")[0].addOnClickHandler(function (e) {
    var code = dafos.codetab.getCode();
    LOG("code:", code, "textarea", textarea);
    code = "\n<scr" + "ipt type='text/javascript'>\n" + code + "\n</sc" + "ript>\n";
    
    if (document.selection) {
      textarea.getElement().focus();
      var selection = document.selection.createRange();
      selection.text = code; 
    } else  if (textarea.getElement().selectionStart != undefined) { 
      var selection_start = textarea.getElement().selectionStart; 
      var selection_end = textarea.getElement().selectionEnd; 
      var current_str = textarea.getValue();
      var str = current_str.substring(0, selection_start) + 
                code + current_str.substring(selection_end, current_str.length);
      textarea.setValue(str);
    } else { 
      textarea.setValue(textarea.getValue() + code); 
    }  
    keylistener();
  });
  
  this.view_tabs_.addTab(name, {
     contentContainer: view.getElement()
  });
  
  var me = this;
  view.$C("view_delete")[0].addOnClickHandler(function (e) {
    me.view_tabs_.removeTab(me.view_tabs_.getSelectedTab().getIndex());
    delete me.views_[name];
  });
  
  this.views_[name] = view;
  return view;
};

dafos.ExportTabUI.prototype.onNewViewClicked = function() {
  var input = new ark.InputDisplay(this.view_parent_);
  var me = this;
  input.show("Name for the new view?", function (desired_name) { 
    if (desired_name) {
      me.addNewView(desired_name);
    }
  });
};

dafos.ExportTabUI.prototype.getNewPreloadRow = function() {
  return e34.renderTemplate(this.preload_template, { 
    "entry_id": this.preload_id_counter++,
    "class_name": (this.preload_id_counter % 2 == 0) ? "even" : "odd"
  });
};

dafos.ExportTabUI.prototype.handleAddPreload = function() {
  this.preload_table.show();
  this.preload_parent.appendChildren(this.getNewPreloadRow());
  gadgets.window.adjustHeight();
};

dafos.ExportTabUI.prototype.getFormData = function() {
  var elems = e34.$C("input");
  var struct = {};
  struct.preloads = [];
  struct.views = {};
  for (var i = 0, elem; elem = elems[i]; i++) {
    if (elem.hasClass("preload")) {
      var num = elem.getTemplateNumber();
      if (num != null) {
        if (!struct.preloads[num]) {
          struct.preloads[num] = {};
        }
        struct.preloads[num][elem.getTemplateId()] = elem.getValue();
      }
    } else if (elem.hasClass("view")) {
      var name = elem.$C("view_name")[0].getValue() || "default";
      var html = elem.$C("view_html")[0].getValue();
      struct.views[name] = {
        "html": html
      };
    } else {
      struct[elem.getId()] = elem.getValue(); 
    }
  }
  return struct;
};

dafos.ExportTabUI.prototype.setFormData = function(data) {
  //Iterate over all the inputs and see if we can assign them values
  var elems = e34.$C("input");
  for (var i = 0, elem; elem = elems[i]; i++) {
    if (!elem.hasClass("preload")) {
      elem.setValue(data[elem.getId()] || "");
    }
  }
  
  //Iterate over the preload data and add rows as needed
  this.preload_parent.removeAllChildren();
  this.preload_id_counter = 0;
  this.preload_table.hide();
  for (var j = 0, preload; preload = data.preloads[j]; j++) {
    this.preload_table.show();
    var row = this.getNewPreloadRow().setParent(this.preload_parent);
    for (var property in preload) {
      if (preload.hasOwnProperty(property)) {
        var id = property + "-" + (this.preload_id_counter - 1);
        e34.$(id).setValue(preload[property]);
      }
    } 
  }
  
  //Clear all but the first view tab
  var view_tabs = this.view_tabs_.getTabs();
  for (var h = view_tabs.length - 1; h > 0; h--) {
    delete this.views_[view_tabs[h].getName()];
    this.view_tabs_.removeTab(h);
  }
  
  //Iterate over the views data
  for (var viewname in data.views) {
    var view = this.addNewView(viewname);
    view.$C("view_html")[0].setValue(data.views[viewname].html);
    view.$C("view_name")[0].setValue(viewname);
  }
  
  //Ensure that for each checkbox, if it is checked, the corresponding select
  //is enabled
  this.forEachFeatureCheckbox(function(checkbox, select, feature_name) { 
    if (checkbox.getValue() == true) {
      select.enable();
    } else {
      select.disable();
    }
  });
  
  gadgets.window.adjustHeight();
};

dafos.ExportTabUI.prototype.getIdToLoad = function() {
  return this.xmlspecs_list_.getValue();
};

dafos.ExportTabUI.prototype.getNameToLoad = function() {
  return this.xmlspecs_list_.getSelectedText();
};

dafos.ExportTabUI.prototype.setCurrentSpec = function(name, id) {  
  if (name && name != "") {
    this.xmlspecs_list_.select(id);
    this.filename_label_.getElement().innerHTML = 
        gadgets.util.escapeString(name);
    this.filename_toolbar_.show();
  } else {
    this.setFormData({});
    this.filename_toolbar_.hide();
    this.preload_parent.removeAllChildren();
    this.preload_id_counter = 0;
    this.preload_table.hide();
  }
  
  gadgets.window.adjustHeight();
};

dafos.ExportTabUI.prototype.renderExportOutput = function(output) {
  this.textbox_.setValue(output);

#if EVILPREVIEWMODE
  //var url = window.location.href.replace(/mid=[0-9]+&/, "");
  var stmatch = /st=([^&#]+)/.exec(window.location.href);  
  var urlmatch = /url=([^&#]+)/.exec(window.location.href);
  var ifrmatch = /^(.*\/gadgets\/ifr)/.exec(window.location.href);
  var viewmatch = /view=([^&#]+)/.exec(window.location.href);
  var syndmatch = /synd=([^&#]+)/.exec(window.location.href);
  var libsmatch = /libs=([^&#]+)/.exec(window.location.href);
  
  var containermatch = /container=([^&#]+)/.exec(window.location.href);
  
  var st = (stmatch) ? decodeURIComponent(stmatch[1]) : "";
  var url = (urlmatch) ? decodeURIComponent(urlmatch[1]) : "";
  var ifr = (ifrmatch) ? ifrmatch[1] : "";
  //var ifr = "http://sandbox.orkut.gmodules.com/gadgets/ifr";
  var view = (viewmatch) ? decodeURIComponent(viewmatch[1]) : "";
  var synd = (syndmatch) ? decodeURIComponent(syndmatch[1]) : "";
  var libs = (libsmatch) ? decodeURIComponent(libsmatch[1]) : "";
  var container = (containermatch) ? decodeURIComponent(containermatch[1]) : "";
  
  this.previewform_.getElement().action = ifr + "#" + [
    "container=" + container, 
    "view=" + view, 
    "url=" + url, 
    "st=" + st, 
    "synd=" + synd,
    "libs=" + libs
  ].join("&");
  
  //this.previewiframe_.getElement().src 
  this.previewform_["st"].setValue(st);
  this.previewform_["view"].setValue(view);
  this.previewform_["synd"].setValue(synd);
  this.previewform_["libs"].setValue(libs);
  this.previewform_["rawxml"].setValue(output);
  this.previewform_["container"].setValue(container);
  
#endif


  this.overlay_.show();
};

dafos.ExportTabUI.prototype.copyElementContent = function(element) {
  elem = e34.$(element).getElement();
  elem.select();
  if (window.clipboardData && clipboardData.setData) {
    clipboardData.setData("text", elem.value);
    LOG("Copied via clipboardData method");
    return true;
  } else if (elem.createTextRange) {
    var range = elem.createTextRange();
    if (range) {
      range.execCommand("Copy");
      LOG("Copied via createTextRange method");
      return true;
    }
  } 
  return false;
}; 

#endif


